
import {generateCacheRequestFunction} from "@/common-data-source/WithCache";
import {TSelectOptions} from "@/common-data-source/type";
import {xhrPostJson} from "@/services";
import {queryDictionaryForSelect} from "@/common-data-source/dictionary";
import {AsyncPageSelectSearchParam} from "@/biz-components/claim-items/components";
import {parsePageResponseToSelect} from "@/common-data-source/parse-page-response-to-select";

/**
 * 过账码下拉选项
 * 每一次都查询全部数据，
 * 然后保存最后一次查询的数据，用于判断是借项还是贷项（isLend 是否为借项）
 * */
type TAccountCode = {name: string, value: string, isLend: boolean};
let lastAccountCodes: Array<TAccountCode> = [];
export const queryAccountCodes = generateCacheRequestFunction<Array<TAccountCode>, void>(function () {
	return xhrPostJson('/ves/acctgCode/page', {pageSize: 10000000, pageNo: 1, queryKeys: {pageCode: 'PostKey_L'}})
		.then((res: any) => {
			const data : Array<TAccountCode> = [];
			for(const item of res.result.content) {
				data.push({
					name: item.name,
					value: item.billingCode,
					isLend: item.brwLoanSign === 'BRW'
				})
			}
			lastAccountCodes = data;
			return data;
		})
});
// 判断一个过账码是不是借项
export function checkAccountCodeIsLend(value: string): boolean {
	let target = lastAccountCodes.find((item) => item.value === value);
	return target? target.isLend : false
}

/**
 * 会科目下拉
 * */

export function queryAccountingSubjectOptionsPage(p: AsyncPageSelectSearchParam): Promise<{data: TSelectOptions, total: number}> {
	return xhrPostJson('/asm/mdm/subject/page', {
		pageNo: p.pageNo,
		pageSize: p.pageSize,
		queryKeys: {keyword: p.keyword}
	})
		.then(parsePageResponseToSelect);
}


/**
 *  查询利润中心下拉数据
 * */
export const queryProfitCenterOptions = generateCacheRequestFunction<TSelectOptions, void>(function () {
	return xhrPostJson('/asm/mdm/shareItem/list', {type: 'COST_CENTER'})
		.then((res: any) => {
			const result: TSelectOptions = [];
			for(let item of res.result || []) {
				result.push({value: item.code, name: item.name})
			}
			return result;
		})
});

/**
 *  查询成本中心下拉数据
 * */
export const queryCostCenterOptions = generateCacheRequestFunction<TSelectOptions, void>(function () {
	return xhrPostJson('/asm/mdm/shareItem/list', {type: 'COST_CENTER'})
		.then((res: any) => {
			const result: TSelectOptions = [];
			for(let item of res.result || []) {
				result.push({value: item.code, name: item.name})
			}
			return result;
		})
});


/**
 * 查询费用类型选项
 * */
export function queryCostsType(): Promise<TSelectOptions> {
	return xhrPostJson('/asm/costType/queryAll', {leafFlag:true,scene:"YFKTK_03",queryKeys:{keyword:""}})
		.then((res: any) => {
			const result: TSelectOptions = [];
			res.result.forEach((item: any) => {
				result.push({
					name: item.name,
					value: item.code
				})
			});
			return result;
		})

}
/**
 * 查询还本类型下拉选项
 * */
export function queryReturnBaseOptions(): Promise<TSelectOptions> {
	return queryDictionaryForSelect('PPMT_TYPE')
}
